using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// NSGA-II多目标优化类 - 参数自动调优框架
    /// 通过Pareto前沿计算和非支配排序优化四个目标函数（收益、风险、成本、稳定性）
    /// </summary>
    public class NSGA2Optimizer
    {
        #region 常量定义

        // NSGA-II算法参数
        public const int DEFAULT_POPULATION_SIZE = 100;     // 默认种群大小
        public const int DEFAULT_MAX_GENERATIONS = 200;     // 默认最大迭代代数
        public const double CROSSOVER_RATE = 0.9;           // 交叉概率
        public const double MUTATION_RATE = 0.1;            // 变异概率
        public const double ETA_C = 20.0;                   // 交叉分布指数
        public const double ETA_M = 20.0;                   // 变异分布指数
        
        // 目标函数权重
        public const double PROFIT_WEIGHT = 0.4;            // 收益权重
        public const double RISK_WEIGHT = 0.3;              // 风险权重  
        public const double EFFICIENCY_WEIGHT = 0.2;        // 效率权重
        public const double STABILITY_WEIGHT = 0.1;         // 稳定性权重

        // 参数范围限制
        public const double MIN_POSITION_SIZE = 0.1;        // 最小仓位
        public const double MAX_POSITION_SIZE = 2.0;        // 最大仓位
        public const double MIN_LEVERAGE = 1.0;             // 最小杠杆
        public const double MAX_LEVERAGE = 200.0;           // 最大杠杆
        public const double MIN_STOP_LOSS = 0.001;          // 最小止损
        public const double MAX_STOP_LOSS = 0.1;            // 最大止损
        public const double MIN_HEDGE_RATIO = 0.0;          // 最小对冲比例
        public const double MAX_HEDGE_RATIO = 1.0;          // 最大对冲比例

        #endregion

        #region 数据结构定义

        /// <summary>
        /// 个体参数结构
        /// </summary>
        public class Individual
        {
            public double[] Parameters { get; set; }         // 参数向量
            public double[] Objectives { get; set; }         // 目标函数值
            public int Rank { get; set; }                    // 非支配等级
            public double CrowdingDistance { get; set; }     // 拥挤度距离
            
            public Individual(int parameterCount)
            {
                Parameters = new double[parameterCount];
                Objectives = new double[4]; // 四个目标函数
                Rank = 0;
                CrowdingDistance = 0.0;
            }

            /// <summary>
            /// 深拷贝个体
            /// </summary>
            public Individual Clone()
            {
                var clone = new Individual(Parameters.Length)
                {
                    Parameters = (double[])Parameters.Clone(),
                    Objectives = (double[])Objectives.Clone(),
                    Rank = Rank,
                    CrowdingDistance = CrowdingDistance
                };
                return clone;
            }
        }

        /// <summary>
        /// 优化结果结构
        /// </summary>
        public class OptimizationResult
        {
            public List<Individual> ParetoFront { get; set; }
            public Individual BestIndividual { get; set; }
            public int Generations { get; set; }
            public double ConvergenceMetric { get; set; }
            public double HyperVolumeIndicator { get; set; }
            public DateTime OptimizationTime { get; set; }
            public TimeSpan ElapsedTime { get; set; }

            /// <summary>
            /// 最优仓位大小（基于最佳个体的第一个参数）
            /// </summary>
            public double OptimalPositionSize
            {
                get
                {
                    if (BestIndividual != null && BestIndividual.Parameters != null && BestIndividual.Parameters.Length > 0)
                    {
                        return BestIndividual.Parameters[0];
                    }
                    return 1.0; // 默认仓位
                }
            }
        }

        /// <summary>
        /// 参数配置结构
        /// </summary>
        public class OptimizationParameters
        {
            public double PositionSize { get; set; }         // 仓位大小
            public double Leverage { get; set; }             // 杠杆比例
            public double StopLoss { get; set; }             // 止损位置
            public double HedgeRatio { get; set; }           // 对冲比例
            public int RetryCount { get; set; }              // 重试次数
        }

        /// <summary>
        /// 优化解决方案
        /// </summary>
        public class Solution
        {
            public double[] Variables { get; set; }          // 决策变量
            public double[] Objectives { get; set; }         // 目标函数值
        }

        /// <summary>
        /// 优化执行结果
        /// </summary>
        public class OptimizeResult
        {
            public List<Solution> ParetoFront { get; set; }  // Pareto前沿解集
            public Solution BestSolution { get; set; }       // 最佳折衷解
            public int Generations { get; set; }             // 迭代代数
            public int FinalPopulationSize { get; set; }     // 最终种群大小
        }

        #endregion

        #region 私有字段

        private readonly IRandomProvider _randomProvider;
        private readonly HistoricalAnalyzer _historicalAnalyzer;
        private readonly RiskMetrics _riskMetrics;
        private readonly KellyCalculator _kellyCalculator;
        private readonly GarchModel _garchModel;
        private readonly List<OptimizationResult> _optimizationHistory;
        private int _populationSize;
        private int _maxGenerations;
        private double _currentMutationRate = MUTATION_RATE;
        private double _currentCrossoverRate = CROSSOVER_RATE;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化NSGA-II多目标优化器
        /// </summary>
        /// <param name="historicalAnalyzer">历史数据分析器</param>
        /// <param name="riskMetrics">风险度量模块</param>
        /// <param name="kellyCalculator">Kelly公式计算器</param>
        /// <param name="garchModel">GARCH模型</param>
        /// <param name="randomProvider">随机数提供器（可选）</param>
        public NSGA2Optimizer(HistoricalAnalyzer historicalAnalyzer, 
                              RiskMetrics riskMetrics, 
                              KellyCalculator kellyCalculator,
                              GarchModel garchModel,
                              IRandomProvider randomProvider = null)
        {
            _historicalAnalyzer = historicalAnalyzer ?? throw new ArgumentNullException(nameof(historicalAnalyzer));
            _riskMetrics = riskMetrics ?? throw new ArgumentNullException(nameof(riskMetrics));
            _kellyCalculator = kellyCalculator ?? throw new ArgumentNullException(nameof(kellyCalculator));
            _garchModel = garchModel ?? throw new ArgumentNullException(nameof(garchModel));
            
            // 使用提供的随机数生成器或创建确定性生成器
            _randomProvider = randomProvider ?? CreateDeterministicRandomProvider();
            
            _optimizationHistory = new List<OptimizationResult>();
            _populationSize = DEFAULT_POPULATION_SIZE;
            _maxGenerations = DEFAULT_MAX_GENERATIONS;
        }

        /// <summary>
        /// 创建确定性随机数提供器
        /// 基于账户ID和日期生成种子，确保结果可重现
        /// </summary>
        private IRandomProvider CreateDeterministicRandomProvider()
        {
            // 基于当前上下文生成确定性种子
            var contextId = $"NSGA2_{DateTime.Today:yyyyMMdd}";
            return DeterministicRandomProvider.CreateForOptimization(contextId);
        }

        #endregion

        #region 核心优化方法

        /// <summary>
        /// 执行NSGA-II多目标优化
        /// </summary>
        /// <param name="historicalData">历史数据</param>
        /// <returns>优化结果</returns>
        public OptimizationResult OptimizeParameters(List<double> historicalData)
        {
            var startTime = DateTime.Now;
            
            try
            {
                // 1. 初始化种群
                var population = InitializePopulation();

                // 2. 评估初始种群
                EvaluatePopulation(population, historicalData);

                // 3. 执行NSGA-II主循环
                for (int generation = 0; generation < _maxGenerations; generation++)
                {
                    // 创建子代种群
                    var offspring = CreateOffspring(population);
                    
                    // 评估子代
                    EvaluatePopulation(offspring, historicalData);
                    
                    // 合并父代和子代
                    var combinedPopulation = population.Concat(offspring).ToList();
                    
                    // 非支配排序
                    var fronts = FastNondominatedSort(combinedPopulation);
                    
                    // 环境选择
                    population = EnvironmentalSelection(fronts);
                    
                    // 检查收敛性
                    if (CheckConvergence(population))
                    {
                        break;
                    }
                }

                // 4. 构建最终结果
                var result = BuildOptimizationResult(population, startTime);
                _optimizationHistory.Add(result);
                
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception($"NSGA-II优化过程中发生错误: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 初始化种群
        /// </summary>
        private List<Individual> InitializePopulation()
        {
            var population = new List<Individual>();
            
            for (int i = 0; i < _populationSize; i++)
            {
                var individual = new Individual(5); // 5个参数
                
                // 使用确定性算法初始化参数
                individual.Parameters[0] = MIN_POSITION_SIZE + _randomProvider.NextDouble() * (MAX_POSITION_SIZE - MIN_POSITION_SIZE);
                individual.Parameters[1] = MIN_LEVERAGE + _randomProvider.NextDouble() * (MAX_LEVERAGE - MIN_LEVERAGE);
                individual.Parameters[2] = MIN_STOP_LOSS + _randomProvider.NextDouble() * (MAX_STOP_LOSS - MIN_STOP_LOSS);
                individual.Parameters[3] = MIN_HEDGE_RATIO + _randomProvider.NextDouble() * (MAX_HEDGE_RATIO - MIN_HEDGE_RATIO);
                individual.Parameters[4] = _randomProvider.Next(1, 11); // 重试次数1-10
                
                population.Add(individual);
            }
            
            return population;
        }

        /// <summary>
        /// 评估种群
        /// </summary>
        private void EvaluatePopulation(List<Individual> population, List<double> historicalData)
        {
            foreach (var individual in population)
            {
                EvaluateIndividual(individual, historicalData);
            }
        }

        /// <summary>
        /// 评估个体的四个目标函数
        /// </summary>
        private void EvaluateIndividual(Individual individual, List<double> historicalData)
        {
            var parameters = ConvertToOptimizationParameters(individual.Parameters);
            
            // 目标函数1: 收益最大化
            individual.Objectives[0] = CalculateProfitObjective(parameters, historicalData);
            
            // 目标函数2: 风险最小化 (转换为最大化问题)
            individual.Objectives[1] = -CalculateRiskObjective(parameters, historicalData);
            
            // 目标函数3: 效率最大化  
            individual.Objectives[2] = CalculateEfficiencyObjective(parameters, historicalData);
            
            // 目标函数4: 稳定性最大化
            individual.Objectives[3] = CalculateStabilityObjective(parameters, historicalData);
        }

        /// <summary>
        /// 计算收益目标函数
        /// </summary>
        private double CalculateProfitObjective(OptimizationParameters parameters, List<double> historicalData)
        {
            try
            {
                if (historicalData == null || historicalData.Count < 30)
                    return 0.0;
                
                // 将价格数据转换为模拟交易数据
                var simulatedTrades = GenerateSimulatedTrades(historicalData);
                
                // 基于Kelly公式计算期望收益
                var winRate = _historicalAnalyzer.CalculateWinRate(simulatedTrades);
                var profitLossRatio = _historicalAnalyzer.CalculateProfitLossRatio(simulatedTrades);
                var stats = _historicalAnalyzer.CalculateDetailedProfitLossStats(simulatedTrades);
                
                if (stats.AverageLoss == 0) return 0.0;
                
                var expectedReturn = (winRate * profitLossRatio - (1 - winRate)) * parameters.PositionSize * parameters.Leverage;
                
                // 考虑对冲成本
                var hedgeCost = parameters.HedgeRatio * 0.001; // 对冲成本
                
                return Math.Max(0.0, expectedReturn - hedgeCost);
            }
            catch
            {
                return 0.0;
            }
        }

        /// <summary>
        /// 计算风险目标函数
        /// </summary>
        private double CalculateRiskObjective(OptimizationParameters parameters, List<double> historicalData)
        {
            try
            {
                if (historicalData == null || historicalData.Count < 30)
                    return 1.0; // 高风险
                
                // 创建临时RiskMetrics实例用于计算
                var tempRiskMetrics = new RiskMetrics();
                
                // 将价格数据添加到RiskMetrics
                foreach (var price in historicalData)
                {
                    tempRiskMetrics.AddPricePoint(price);
                }
                
                // 计算基于仓位价值的VaR风险
                double positionValue = parameters.PositionSize * parameters.Leverage * 1000; // 假设每手1000单位
                var var95 = tempRiskMetrics.CalculateHistoricalVaR(0.95, positionValue);
                var cvar95 = tempRiskMetrics.CalculateCVaR(0.95, positionValue);
                
                // 杠杆调整风险
                var leverageAdjustedRisk = (Math.Abs(var95) + Math.Abs(cvar95)) / positionValue;
                
                // 对冲风险减免
                var hedgeAdjustment = 1.0 - parameters.HedgeRatio * 0.8; // 对冲可减少80%风险
                
                return Math.Max(0.001, leverageAdjustedRisk * hedgeAdjustment);
            }
            catch
            {
                return 1.0; // 发生异常时返回高风险
            }
        }

        /// <summary>
        /// 计算效率目标函数
        /// </summary>
        private double CalculateEfficiencyObjective(OptimizationParameters parameters, List<double> historicalData)
        {
            try
            {
                if (historicalData == null || historicalData.Count < 30)
                    return 0.0;
                
                // 基于夏普比率计算效率
                var returns = historicalData.ToArray();
                var avgReturn = returns.Average();
                var stdReturn = Math.Sqrt(returns.Select(r => Math.Pow(r - avgReturn, 2)).Average());
                
                if (stdReturn == 0) return 0.0;
                
                var sharpeRatio = avgReturn / stdReturn;
                
                // 考虑执行效率
                var executionEfficiency = 1.0 - (parameters.RetryCount - 1) * 0.05; // 重试次数影响效率
                var leverageEfficiency = Math.Min(1.0, 50.0 / parameters.Leverage); // 杠杆效率
                
                return Math.Max(0.0, sharpeRatio * executionEfficiency * leverageEfficiency);
            }
            catch
            {
                return 0.0;
            }
        }

        /// <summary>
        /// 计算稳定性目标函数
        /// </summary>
        private double CalculateStabilityObjective(OptimizationParameters parameters, List<double> historicalData)
        {
            try
            {
                if (historicalData == null || historicalData.Count < 30)
                    return 0.0;
                
                // 基于收益稳定性计算
                var returns = historicalData.ToArray();
                var avgReturn = returns.Average();
                
                // 计算收益的变异系数
                var stdReturn = Math.Sqrt(returns.Select(r => Math.Pow(r - avgReturn, 2)).Average());
                var coefficientOfVariation = Math.Abs(avgReturn) > 1e-10 ? stdReturn / Math.Abs(avgReturn) : 1.0;
                
                // 稳定性得分 (变异系数越小，稳定性越高)
                var stabilityScore = 1.0 / (1.0 + coefficientOfVariation);
                
                // 对冲比例提升稳定性
                var hedgeStabilityBonus = parameters.HedgeRatio * 0.2;
                
                // 杠杆过高降低稳定性
                var leveragePenalty = parameters.Leverage > 50 ? (parameters.Leverage - 50) / 1000.0 : 0.0;
                
                return Math.Max(0.0, stabilityScore + hedgeStabilityBonus - leveragePenalty);
            }
            catch
            {
                return 0.0;
            }
        }

        #endregion

        #region NSGA-II核心算法

        /// <summary>
        /// 快速非支配排序
        /// </summary>
        private List<List<Individual>> FastNondominatedSort(List<Individual> population)
        {
            var fronts = new List<List<Individual>>();
            var dominationCount = new Dictionary<Individual, int>();
            var dominatedSolutions = new Dictionary<Individual, List<Individual>>();
            
            // 初始化
            foreach (var individual in population)
            {
                dominationCount[individual] = 0;
                dominatedSolutions[individual] = new List<Individual>();
            }
            
            var firstFront = new List<Individual>();
            
            // 计算支配关系
            for (int i = 0; i < population.Count; i++)
            {
                for (int j = 0; j < population.Count; j++)
                {
                    if (i == j) continue;
                    
                    var individual1 = population[i];
                    var individual2 = population[j];
                    
                    if (Dominates(individual1, individual2))
                    {
                        dominatedSolutions[individual1].Add(individual2);
                    }
                    else if (Dominates(individual2, individual1))
                    {
                        dominationCount[individual1]++;
                    }
                }
                
                if (dominationCount[population[i]] == 0)
                {
                    population[i].Rank = 0;
                    firstFront.Add(population[i]);
                }
            }
            
            fronts.Add(firstFront);
            
            // 生成后续前沿
            int frontIndex = 0;
            while (fronts[frontIndex].Count > 0)
            {
                var nextFront = new List<Individual>();
                
                foreach (var individual in fronts[frontIndex])
                {
                    foreach (var dominated in dominatedSolutions[individual])
                    {
                        dominationCount[dominated]--;
                        if (dominationCount[dominated] == 0)
                        {
                            dominated.Rank = frontIndex + 1;
                            nextFront.Add(dominated);
                        }
                    }
                }
                
                frontIndex++;
                fronts.Add(nextFront);
            }
            
            // 移除空的最后一层
            if (fronts[fronts.Count - 1].Count == 0)
            {
                fronts.RemoveAt(fronts.Count - 1);
            }
            
            return fronts;
        }

        /// <summary>
        /// 检查个体1是否支配个体2
        /// </summary>
        private bool Dominates(Individual individual1, Individual individual2)
        {
            bool atLeastOneBetter = false;
            
            for (int i = 0; i < individual1.Objectives.Length; i++)
            {
                if (individual1.Objectives[i] < individual2.Objectives[i])
                {
                    return false; // 有目标函数更差
                }
                if (individual1.Objectives[i] > individual2.Objectives[i])
                {
                    atLeastOneBetter = true;
                }
            }
            
            return atLeastOneBetter;
        }

        /// <summary>
        /// 计算拥挤度距离
        /// </summary>
        private void CalculateCrowdingDistance(List<Individual> front)
        {
            if (front.Count == 0) return;
            
            int numObjectives = front[0].Objectives.Length;
            
            // 初始化拥挤度距离
            foreach (var individual in front)
            {
                individual.CrowdingDistance = 0.0;
            }
            
            for (int obj = 0; obj < numObjectives; obj++)
            {
                // 按第obj个目标函数排序
                front.Sort((x, y) => x.Objectives[obj].CompareTo(y.Objectives[obj]));
                
                // 边界个体设置为无穷大
                front[0].CrowdingDistance = double.PositiveInfinity;
                front[front.Count - 1].CrowdingDistance = double.PositiveInfinity;
                
                // 计算目标函数的范围
                double objRange = front[front.Count - 1].Objectives[obj] - front[0].Objectives[obj];
                if (objRange == 0) continue;
                
                // 计算中间个体的拥挤度距离
                for (int i = 1; i < front.Count - 1; i++)
                {
                    if (double.IsInfinity(front[i].CrowdingDistance)) continue;
                    
                    double distance = (front[i + 1].Objectives[obj] - front[i - 1].Objectives[obj]) / objRange;
                    front[i].CrowdingDistance += distance;
                }
            }
        }

        /// <summary>
        /// 创建子代种群
        /// </summary>
        private List<Individual> CreateOffspring(List<Individual> population)
        {
            var offspring = new List<Individual>();
            
            while (offspring.Count < _populationSize)
            {
                // 锦标赛选择两个父代
                var parent1 = TournamentSelection(population);
                var parent2 = TournamentSelection(population);
                
                // 交叉操作
                var (child1, child2) = SimulatedBinaryCrossover(parent1, parent2);
                
                // 变异操作
                PolynomialMutation(child1);
                PolynomialMutation(child2);
                
                offspring.Add(child1);
                if (offspring.Count < _populationSize)
                {
                    offspring.Add(child2);
                }
            }
            
            return offspring;
        }

        /// <summary>
        /// 锦标赛选择
        /// </summary>
        private Individual TournamentSelection(List<Individual> population)
        {
            var tournamentSize = Math.Min(4, population.Count);
            var tournament = new List<Individual>();
            
            for (int i = 0; i < tournamentSize; i++)
            {
                tournament.Add(population[_randomProvider.Next(population.Count)]);
            }
            
            // 选择最好的个体（先比较rank，再比较crowding distance）
            return tournament.OrderBy(x => x.Rank)
                            .ThenByDescending(x => x.CrowdingDistance)
                            .First();
        }

        /// <summary>
        /// 模拟二进制交叉
        /// </summary>
        private (Individual, Individual) SimulatedBinaryCrossover(Individual parent1, Individual parent2)
        {
            var child1 = parent1.Clone();
            var child2 = parent2.Clone();
            
            if (_randomProvider.NextDouble() <= CROSSOVER_RATE)
            {
                for (int i = 0; i < parent1.Parameters.Length; i++)
                {
                    if (_randomProvider.NextDouble() <= 0.5)
                    {
                        double beta = CalculateBeta(ETA_C);
                        
                        child1.Parameters[i] = 0.5 * ((1 + beta) * parent1.Parameters[i] + (1 - beta) * parent2.Parameters[i]);
                        child2.Parameters[i] = 0.5 * ((1 - beta) * parent1.Parameters[i] + (1 + beta) * parent2.Parameters[i]);
                        
                        // 边界处理
                        child1.Parameters[i] = BoundParameter(child1.Parameters[i], i);
                        child2.Parameters[i] = BoundParameter(child2.Parameters[i], i);
                    }
                }
            }
            
            return (child1, child2);
        }

        /// <summary>
        /// 多项式变异
        /// </summary>
        private void PolynomialMutation(Individual individual)
        {
            for (int i = 0; i < individual.Parameters.Length; i++)
            {
                if (_randomProvider.NextDouble() <= MUTATION_RATE)
                {
                    double delta = CalculateDelta(ETA_M);
                    individual.Parameters[i] = individual.Parameters[i] + delta * GetParameterRange(i);
                    individual.Parameters[i] = BoundParameter(individual.Parameters[i], i);
                }
            }
        }

        /// <summary>
        /// 环境选择
        /// </summary>
        private List<Individual> EnvironmentalSelection(List<List<Individual>> fronts)
        {
            var newPopulation = new List<Individual>();
            
            foreach (var front in fronts)
            {
                if (newPopulation.Count + front.Count <= _populationSize)
                {
                    newPopulation.AddRange(front);
                }
                else
                {
                    // 计算拥挤度距离
                    CalculateCrowdingDistance(front);
                    
                    // 按拥挤度距离排序选择
                    var remainingSlots = _populationSize - newPopulation.Count;
                    var selectedIndividuals = front.OrderByDescending(x => x.CrowdingDistance)
                                                  .Take(remainingSlots);
                    newPopulation.AddRange(selectedIndividuals);
                    break;
                }
            }
            
            return newPopulation;
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 参数转换
        /// </summary>
        private OptimizationParameters ConvertToOptimizationParameters(double[] parameters)
        {
            return new OptimizationParameters
            {
                PositionSize = parameters[0],
                Leverage = parameters[1],
                StopLoss = parameters[2],
                HedgeRatio = parameters[3],
                RetryCount = (int)Math.Round(parameters[4])
            };
        }

        /// <summary>
        /// 参数边界处理
        /// </summary>
        private double BoundParameter(double value, int parameterIndex)
        {
            switch (parameterIndex)
            {
                case 0: return Math.Max(MIN_POSITION_SIZE, Math.Min(MAX_POSITION_SIZE, value));
                case 1: return Math.Max(MIN_LEVERAGE, Math.Min(MAX_LEVERAGE, value));
                case 2: return Math.Max(MIN_STOP_LOSS, Math.Min(MAX_STOP_LOSS, value));
                case 3: return Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, value));
                case 4: return Math.Max(1.0, Math.Min(10.0, Math.Round(value)));
                default: return value;
            }
        }

        /// <summary>
        /// 获取参数范围
        /// </summary>
        private double GetParameterRange(int parameterIndex)
        {
            switch (parameterIndex)
            {
                case 0: return MAX_POSITION_SIZE - MIN_POSITION_SIZE;
                case 1: return MAX_LEVERAGE - MIN_LEVERAGE;
                case 2: return MAX_STOP_LOSS - MIN_STOP_LOSS;
                case 3: return MAX_HEDGE_RATIO - MIN_HEDGE_RATIO;
                case 4: return 9.0; // 重试次数1-10
                default: return 1.0;
            }
        }

        /// <summary>
        /// 计算Beta值（交叉用）
        /// </summary>
        private double CalculateBeta(double etaC)
        {
            double u = _randomProvider.NextDouble();
            if (u <= 0.5)
            {
                return Math.Pow(2.0 * u, 1.0 / (etaC + 1.0));
            }
            else
            {
                return Math.Pow(1.0 / (2.0 * (1.0 - u)), 1.0 / (etaC + 1.0));
            }
        }

        /// <summary>
        /// 计算Delta值（变异用）
        /// </summary>
        private double CalculateDelta(double etaM)
        {
            double u = _randomProvider.NextDouble();
            if (u <= 0.5)
            {
                return Math.Pow(2.0 * u, 1.0 / (etaM + 1.0)) - 1.0;
            }
            else
            {
                return 1.0 - Math.Pow(2.0 * (1.0 - u), 1.0 / (etaM + 1.0));
            }
        }

        /// <summary>
        /// 检查收敛性
        /// </summary>
        private bool CheckConvergence(List<Individual> population)
        {
            // 简单的收敛检查：前沿个体目标函数值的方差
            var firstFront = population.Where(x => x.Rank == 0).ToList();
            if (firstFront.Count < 2) return false;
            
            var avgObjectives = new double[4];
            foreach (var individual in firstFront)
            {
                for (int i = 0; i < 4; i++)
                {
                    avgObjectives[i] += individual.Objectives[i];
                }
            }
            
            for (int i = 0; i < 4; i++)
            {
                avgObjectives[i] /= firstFront.Count;
            }
            
            var variance = 0.0;
            foreach (var individual in firstFront)
            {
                for (int i = 0; i < 4; i++)
                {
                    variance += Math.Pow(individual.Objectives[i] - avgObjectives[i], 2);
                }
            }
            variance /= (firstFront.Count * 4);
            
            return variance < 1e-6; // 方差阈值
        }

        /// <summary>
        /// 构建优化结果
        /// </summary>
        private OptimizationResult BuildOptimizationResult(List<Individual> population, DateTime startTime)
        {
            var paretoFront = population.Where(x => x.Rank == 0).ToList();
            
            // 找到综合得分最高的个体作为最佳个体
            var bestIndividual = paretoFront.OrderByDescending(x => 
                PROFIT_WEIGHT * x.Objectives[0] + 
                RISK_WEIGHT * x.Objectives[1] + 
                EFFICIENCY_WEIGHT * x.Objectives[2] + 
                STABILITY_WEIGHT * x.Objectives[3]).FirstOrDefault() ?? population.First();
            
            return new OptimizationResult
            {
                ParetoFront = paretoFront,
                BestIndividual = bestIndividual,
                Generations = _maxGenerations,
                ConvergenceMetric = CalculateConvergenceMetric(paretoFront),
                HyperVolumeIndicator = CalculateHyperVolume(paretoFront),
                OptimizationTime = DateTime.Now,
                ElapsedTime = DateTime.Now - startTime
            };
        }

        /// <summary>
        /// 计算收敛性度量
        /// </summary>
        private double CalculateConvergenceMetric(List<Individual> paretoFront)
        {
            if (paretoFront.Count < 2) return 0.0;
            
            double totalDistance = 0.0;
            for (int i = 0; i < paretoFront.Count - 1; i++)
            {
                for (int j = i + 1; j < paretoFront.Count; j++)
                {
                    double distance = 0.0;
                    for (int k = 0; k < 4; k++)
                    {
                        distance += Math.Pow(paretoFront[i].Objectives[k] - paretoFront[j].Objectives[k], 2);
                    }
                    totalDistance += Math.Sqrt(distance);
                }
            }
            
            return totalDistance / (paretoFront.Count * (paretoFront.Count - 1) / 2.0);
        }

        /// <summary>
        /// 计算超体积指标
        /// </summary>
        private double CalculateHyperVolume(List<Individual> paretoFront)
        {
            if (paretoFront.Count == 0) return 0.0;
            
            // 简化的超体积计算（使用参考点）
            var referencePoint = new double[] { 0.0, 0.0, 0.0, 0.0 };
            
            double hyperVolume = 0.0;
            foreach (var individual in paretoFront)
            {
                double volume = 1.0;
                for (int i = 0; i < 4; i++)
                {
                    volume *= Math.Max(0.0, individual.Objectives[i] - referencePoint[i]);
                }
                hyperVolume += volume;
            }
            
            return hyperVolume;
        }

        #endregion

        #region 公开接口方法

        /// <summary>
        /// 获取最优参数配置
        /// </summary>
        public OptimizationParameters GetOptimalParameters(List<double> historicalData)
        {
            var result = OptimizeParameters(historicalData);
            return ConvertToOptimizationParameters(result.BestIndividual.Parameters);
        }

        /// <summary>
        /// 获取Pareto前沿解集
        /// </summary>
        public List<OptimizationParameters> GetParetoOptimalSolutions(List<double> historicalData)
        {
            var result = OptimizeParameters(historicalData);
            return result.ParetoFront.Select(x => ConvertToOptimizationParameters(x.Parameters)).ToList();
        }

        /// <summary>
        /// 配置优化算法参数
        /// </summary>
        public void ConfigureAlgorithmParameters(int populationSize, int maxGenerations)
        {
            _populationSize = Math.Max(20, populationSize);
            _maxGenerations = Math.Max(10, maxGenerations);
        }

        /// <summary>
        /// 获取优化历史
        /// </summary>
        public List<OptimizationResult> GetOptimizationHistory()
        {
            return _optimizationHistory.ToList();
        }

        /// <summary>
        /// 执行NSGA-II多目标优化
        /// 优化仓位大小，考虑夏普比率和波动率
        /// </summary>
        /// <param name="currentPosition">当前仓位</param>
        /// <param name="sharpeRatio">夏普比率</param>
        /// <param name="volatility">波动率</param>
        /// <param name="populationSize">种群大小</param>
        /// <param name="maxGenerations">最大迭代代数</param>
        /// <returns>优化结果包含Pareto前沿</returns>
        public OptimizeResult Optimize(
            double currentPosition,
            double sharpeRatio,
            double volatility,
            int populationSize = DEFAULT_POPULATION_SIZE,
            int maxGenerations = DEFAULT_MAX_GENERATIONS)
        {
            // 配置算法参数
            ConfigureAlgorithmParameters(populationSize, maxGenerations);

            // 初始化种群
            var population = InitializePopulation(populationSize, currentPosition);

            // 迭代优化
            for (int generation = 0; generation < maxGenerations; generation++)
            {
                // 评估目标函数
                EvaluateObjectives(population, sharpeRatio, volatility);

                // 非支配排序
                NonDominatedSort(population);

                // 计算拥挤度距离
                CalculateCrowdingDistance(population);

                // 选择、交叉、变异生成新种群
                var offspring = GenerateOffspring(population);

                // 合并父代和子代
                var combinedPop = new List<Individual>(population);
                combinedPop.AddRange(offspring);

                // 环境选择（精英保留）
                population = EnvironmentalSelection(combinedPop, populationSize);

                // 自适应参数调整
                AdaptParameters(generation, maxGenerations);
            }

            // 提取Pareto前沿
            var paretoFront = population
                .Where(ind => ind.Rank == 1)
                .Select(ind => new Solution
                {
                    Variables = ind.Parameters,
                    Objectives = ind.Objectives
                })
                .ToList();

            return new OptimizeResult
            {
                ParetoFront = paretoFront,
                BestSolution = SelectBestCompromise(paretoFront),
                Generations = maxGenerations,
                FinalPopulationSize = population.Count
            };
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 初始化种群（带参数版本）
        /// </summary>
        private List<Individual> InitializePopulation(int populationSize, double currentPosition)
        {
            var population = new List<Individual>();
            for (int i = 0; i < populationSize; i++)
            {
                var individual = new Individual(4); // 4个参数：仓位、杠杆、止损、对冲

                // 随机初始化参数
                individual.Parameters[0] = currentPosition * (0.5 + _randomProvider.NextDouble() * 1.0); // 仓位
                individual.Parameters[1] = 1.0 + _randomProvider.NextDouble() * 10.0; // 杠杆
                individual.Parameters[2] = 0.01 + _randomProvider.NextDouble() * 0.09; // 止损
                individual.Parameters[3] = _randomProvider.NextDouble(); // 对冲比例

                population.Add(individual);
            }
            return population;
        }

        /// <summary>
        /// 评估目标函数
        /// </summary>
        private void EvaluateObjectives(List<Individual> population, double sharpeRatio, double volatility)
        {
            foreach (var individual in population)
            {
                // 计算4个目标函数
                individual.Objectives = new double[4];

                // 目标1：最大化收益（基于夏普比率）
                individual.Objectives[0] = -sharpeRatio * individual.Parameters[0]; // 最小化（取负值）

                // 目标2：最小化风险（基于波动率）
                individual.Objectives[1] = volatility * individual.Parameters[1];

                // 目标3：最小化成本
                individual.Objectives[2] = individual.Parameters[2] * 100; // 止损成本

                // 目标4：最大化稳定性
                individual.Objectives[3] = Math.Abs(individual.Parameters[3] - 0.5) * 2; // 对冲偏离度
            }
        }

        /// <summary>
        /// 非支配排序
        /// </summary>
        private void NonDominatedSort(List<Individual> population)
        {
            // 简化版非支配排序
            foreach (var individual in population)
            {
                individual.Rank = 1; // 简化处理，全部设为第一前沿
            }
        }

        /// <summary>
        /// 生成子代
        /// </summary>
        private List<Individual> GenerateOffspring(List<Individual> population)
        {
            var offspring = new List<Individual>();

            // 通过交叉和变异生成子代
            for (int i = 0; i < population.Count; i += 2)
            {
                if (i + 1 < population.Count)
                {
                    var parent1 = population[i];
                    var parent2 = population[i + 1];

                    // 简化的交叉操作
                    var child1 = parent1.Clone();
                    var child2 = parent2.Clone();

                    // 交叉
                    if (_randomProvider.NextDouble() < _currentCrossoverRate)
                    {
                        for (int j = 0; j < child1.Parameters.Length; j++)
                        {
                            double alpha = _randomProvider.NextDouble();
                            double temp = child1.Parameters[j];
                            child1.Parameters[j] = alpha * parent1.Parameters[j] + (1 - alpha) * parent2.Parameters[j];
                            child2.Parameters[j] = alpha * parent2.Parameters[j] + (1 - alpha) * temp;
                        }
                    }

                    // 变异
                    if (_randomProvider.NextDouble() < _currentMutationRate)
                    {
                        int mutationPoint = _randomProvider.Next(child1.Parameters.Length);
                        child1.Parameters[mutationPoint] += (_randomProvider.NextDouble() - 0.5) * 0.1;
                        child2.Parameters[mutationPoint] += (_randomProvider.NextDouble() - 0.5) * 0.1;
                    }

                    offspring.Add(child1);
                    offspring.Add(child2);
                }
            }

            return offspring;
        }

        /// <summary>
        /// 环境选择（带参数版本）
        /// </summary>
        private List<Individual> EnvironmentalSelection(List<Individual> combinedPop, int populationSize)
        {
            // 按Rank排序，选择最优的
            return combinedPop
                .OrderBy(i => i.Rank)
                .ThenByDescending(i => i.CrowdingDistance)
                .Take(populationSize)
                .ToList();
        }

        /// <summary>
        /// 自适应参数调整
        /// </summary>
        private void AdaptParameters(int currentGeneration, int maxGenerations)
        {
            // 随着迭代进程调整参数
            double progress = (double)currentGeneration / maxGenerations;

            // 动态调整变异率（逐渐降低）
            _currentMutationRate = MUTATION_RATE * (1.0 - progress * 0.5);

            // 动态调整交叉率（保持稳定）
            _currentCrossoverRate = CROSSOVER_RATE;
        }

        /// <summary>
        /// 选择最佳折衷解
        /// 从Pareto前沿中选择最平衡的解决方案
        /// </summary>
        private Solution SelectBestCompromise(List<Solution> paretoFront)
        {
            if (paretoFront == null || paretoFront.Count == 0)
                return null;

            // 选择目标函数值最平衡的解（最小化目标函数的标准差）
            return paretoFront.OrderBy(s =>
            {
                double mean = s.Objectives.Average();
                double variance = s.Objectives.Sum(o => Math.Pow(o - mean, 2)) / s.Objectives.Length;
                return Math.Sqrt(variance);
            }).FirstOrDefault();
        }

        /// <summary>
        /// 将价格数据转换为模拟交易数据
        /// </summary>
        private List<TradeModel> GenerateSimulatedTrades(List<double> priceData)
        {
            var trades = new List<TradeModel>();
            if (priceData.Count < 2) return trades;

            for (int i = 1; i < priceData.Count; i++)
            {
                var currentPrice = priceData[i];
                var previousPrice = priceData[i - 1];
                var priceChange = currentPrice - previousPrice;
                
                // 创建模拟交易
                var trade = new TradeModel
                {
                    Time = DateTime.Now.AddDays(-priceData.Count + i),
                    Profit = priceChange,
                    Symbol = "SIMULATED",
                    Volume = 1.0,
                    Price = currentPrice
                };
                
                trades.Add(trade);
            }

            return trades;
        }

        /// <summary>
        /// 将价格数据转换为收益率数据
        /// </summary>
        private List<double> ConvertToReturns(List<double> priceData)
        {
            var returns = new List<double>();
            if (priceData.Count < 2) return returns;

            for (int i = 1; i < priceData.Count; i++)
            {
                if (priceData[i - 1] != 0)
                {
                    double returnValue = (priceData[i] - priceData[i - 1]) / priceData[i - 1];
                    returns.Add(returnValue);
                }
            }

            return returns;
        }

        #endregion
    }
}
